export class Sqlite {
	
	constructor() {
		this.init();
	}
	
	/* 本地数据库配置 */
	config = {
		name: 'pro',
		path: '_doc/pro.db',
	}

	sql = {
		/** 创建 Token 表结构 */
		createTokenTable: async () => this.executeSql(`CREATE TABLE IF NOT EXISTS token (
			id INTEGER PRIMARY KEY AUTOINCREMENT,
			token TEXT
		);`),
		/* 获取 Token 表数据 */
		getTokenTable: () => this.selectSql(`SELECT * FROM token WHERE id = 1;`),
		
		/* 插入 Token 记录 */
		insertToken: (token: string, id: number) => this.executeSql(`INSERT INTO token (token, id) VALUES ('${token}', ${id});`),

		/* 更新 Token 记录 */
		updateTokenById: (id: number, newToken: string) => this.executeSql(`UPDATE token SET token = '${newToken}' WHERE id = ${id};`),

		/* 删除 Token 记录 */
		deleteTokenById: (id: number) => this.executeSql(`DELETE FROM token WHERE id = ${id};`),
	};
	
	/* 初始化数据库 */
	async init () {
		const status: boolean = await this.createOpenDB();
		/* 数据库已经初始化且创建成功 */
		if (status) {
			await Promise.all([
				this.sql.createTokenTable(),
			]);
		}
	}
	
	/** 创建并打开数据库 */
	async createOpenDB(): Promise<boolean> {
		return new Promise((resolve) => {
			plus.sqlite.openDatabase({
				...this.config,
				success: () => {
					console.log('执行 sqlite 成功');
					resolve(true);
				},
				fail: () => {
					resolve(false);
				}
			});
		})
	}
	
	/* 执行语句 */
	async executeSql(sql: string | string[]) {
		return new Promise((resolve) => {
			plus.sqlite.executeSql({
				name: this.config.name,
				sql,
				success: () => {
					console.log('执行 sqlite 成功');
					resolve(true);
				},
				fail: () => resolve(false),
			} as any);
		})
	}
	
	/** 查询语句 */
	async selectSql(sql: string) {
		return new Promise((resolve) => {
			plus.sqlite.selectSql({
				name: this.config.name,
				sql,
				success: (data) => {
					console.log('查询完成');
					resolve(data);
				},
				fail: () => resolve(false),
			});
		})
	}
}